package com.yonghui.springsecurityoauth2demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/custom")
public class CustomTokenController {

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;

    @GetMapping("/check_token")
    public ResponseEntity<?> checkToken(@RequestParam("token") String token) {
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Token not found");
        }
        if (accessToken.isExpired()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Token expired");
        }
        // 如果需要，可以返回其他关于 token 的信息
        return ResponseEntity.ok(accessToken);
    }

    @PostMapping("/revoke_token")
    public ResponseEntity<?> revokeToken(@RequestParam("token") String token) {
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
        if (accessToken == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Token not found");
        }
        tokenStore.removeAccessToken(accessToken);
        return ResponseEntity.ok("Token revoked successfully");
    }
}
